﻿using BLL.BatchBLL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MDMUI
{
    public partial class createProduction : Form
    {
        private CreateProductionBLL createProductionBll = new CreateProductionBLL(); // 创建 BLL 层实例
        private List<QueryBatchAndWorkOrderItem> currentData = new List<QueryBatchAndWorkOrderItem>(); // 用于存储当前查询结果的列表
        private List<Model.Carrier> currentCarrierData = new List<Model.Carrier>(); // 用于存储当前查询结果的载具数据列表

        public createProduction()
        {
            InitializeComponent();
            InitializeDataGridView(); // 初始化 DataGridView 组件
            LoadEventTimes(); // 加载 EventTime 数据到 ComboBox
            InitializeDataGridView2(); // 初始化 DataGridView 组件
            LoadCarrierData(); // 加载载具数据到 DataGridView2
        }

        private void InitializeDataGridView()
        {
            // 清空现有列
            dataGridView1.Columns.Clear();

            // 设置 DataGridView 的属性
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.ReadOnly = true; // 设置为只读，防止用户修改数据
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 设置选择模式为整行选择

            // 添加列
            // 批次号
            DataGridViewTextBoxColumn colBatchId = new DataGridViewTextBoxColumn();
            colBatchId.Name = "BatchId";
            colBatchId.HeaderText = "批次号";
            colBatchId.DataPropertyName = "BatchId";
            colBatchId.Width = 80;
            dataGridView1.Columns.Add(colBatchId);

            // 批次类型
            DataGridViewTextBoxColumn colBatchType = new DataGridViewTextBoxColumn();
            colBatchType.Name = "BatchType";
            colBatchType.HeaderText = "批次类型";
            colBatchType.DataPropertyName = "BatchType";
            colBatchType.Width = 80;
            dataGridView1.Columns.Add(colBatchType);

            // 单位
            DataGridViewTextBoxColumn colUnit = new DataGridViewTextBoxColumn();
            colUnit.Name = "Unit";
            colUnit.HeaderText = "单位";
            colUnit.DataPropertyName = "Unit";
            colUnit.Width = 60;
            dataGridView1.Columns.Add(colUnit);

            // 批次数量
            DataGridViewTextBoxColumn colBatchQuantity = new DataGridViewTextBoxColumn();
            colBatchQuantity.Name = "Quantity";
            colBatchQuantity.HeaderText = "批次数量";
            colBatchQuantity.DataPropertyName = "Quantity";
            colBatchQuantity.Width = 80;
            dataGridView1.Columns.Add(colBatchQuantity);

            // 子产品数量
            DataGridViewTextBoxColumn colSubProductQuantity = new DataGridViewTextBoxColumn();
            colSubProductQuantity.Name = "SubQuantity";
            colSubProductQuantity.HeaderText = "子产品数量";
            colSubProductQuantity.DataPropertyName = "SubQuantity";
            colSubProductQuantity.Width = 100;
            dataGridView1.Columns.Add(colSubProductQuantity);

            // 在制品状态
            DataGridViewTextBoxColumn colWorkInProcessStatus = new DataGridViewTextBoxColumn();
            colWorkInProcessStatus.Name = "LockStatus";
            colWorkInProcessStatus.HeaderText = "在制品状态";
            colWorkInProcessStatus.DataPropertyName = "LockStatus";
            colWorkInProcessStatus.Width = 100;
            dataGridView1.Columns.Add(colWorkInProcessStatus);

            // 投产状态
            DataGridViewTextBoxColumn colLockStatus = new DataGridViewTextBoxColumn();
            colLockStatus.Name = "LockStatus";
            colLockStatus.HeaderText = "投产状态";
            colLockStatus.DataPropertyName = "LockStatus";
            colLockStatus.Width = 80;
            dataGridView1.Columns.Add(colLockStatus);

            // 工单号
            DataGridViewTextBoxColumn colWorkOrderNumber = new DataGridViewTextBoxColumn();
            colWorkOrderNumber.Name = "WorkOrderNumber";
            colWorkOrderNumber.HeaderText = "工单号";
            colWorkOrderNumber.DataPropertyName = "WorkOrderNumber";
            colWorkOrderNumber.Width = 80;
            dataGridView1.Columns.Add(colWorkOrderNumber);

            // 产品编号
            DataGridViewTextBoxColumn colProductNumber = new DataGridViewTextBoxColumn();
            colProductNumber.Name = "ProductId";
            colProductNumber.HeaderText = "产品编号";
            colProductNumber.DataPropertyName = "ProductId";
            colProductNumber.Width = 80;
            dataGridView1.Columns.Add(colProductNumber);

            // 工艺流程号
            DataGridViewTextBoxColumn colProcessNumber = new DataGridViewTextBoxColumn();
            colProcessNumber.Name = "TotalProcessId";
            colProcessNumber.HeaderText = "工艺流程号";
            colProcessNumber.DataPropertyName = "TotalProcessId";
            colProcessNumber.Width = 100;
            dataGridView1.Columns.Add(colProcessNumber);

            // 工艺流程版本
            DataGridViewTextBoxColumn colProcessVersion = new DataGridViewTextBoxColumn();
            colProcessVersion.Name = "ProcessVersion";
            colProcessVersion.HeaderText = "工艺流程版本";
            colProcessVersion.DataPropertyName = "ProcessVersion";
            colProcessVersion.Width = 100;
            dataGridView1.Columns.Add(colProcessVersion);

            // 工站号
            DataGridViewTextBoxColumn colWorkstationNumber = new DataGridViewTextBoxColumn();
            colWorkstationNumber.Name = "WorkstationNumber";
            colWorkstationNumber.HeaderText = "工站号";
            colWorkstationNumber.DataPropertyName = "WorkstationNumber";
            colWorkstationNumber.Width = 80;
            dataGridView1.Columns.Add(colWorkstationNumber);

            // 工站版本
            DataGridViewTextBoxColumn colWorkstationVersion = new DataGridViewTextBoxColumn();
            colWorkstationVersion.Name = "WorkstationVersion";
            colWorkstationVersion.HeaderText = "工站版本";
            colWorkstationVersion.DataPropertyName = "WorkstationVersion";
            colWorkstationVersion.Width = 80;
            dataGridView1.Columns.Add(colWorkstationVersion);

            // 描述
            DataGridViewTextBoxColumn colDescription = new DataGridViewTextBoxColumn();
            colDescription.Name = "Description";
            colDescription.HeaderText = "描述";
            colDescription.DataPropertyName = "Description";
            colDescription.Width = 150;
            dataGridView1.Columns.Add(colDescription);

            // 工厂
            DataGridViewTextBoxColumn colFactory = new DataGridViewTextBoxColumn();
            colFactory.Name = "Factory";
            colFactory.HeaderText = "工厂";
            colFactory.DataPropertyName = "Factory";
            colFactory.Width = 80;
            dataGridView1.Columns.Add(colFactory);

            // 事件发生时间
            DataGridViewTextBoxColumn colEventTime = new DataGridViewTextBoxColumn();
            colEventTime.Name = "EventTime";
            colEventTime.HeaderText = "事件发生时间";
            colEventTime.DataPropertyName = "EventTime";
            colEventTime.Width = 120;
            dataGridView1.Columns.Add(colEventTime);

            // 事件用户
            DataGridViewTextBoxColumn colTimeUser = new DataGridViewTextBoxColumn();
            colTimeUser.Name = "EventUser";
            colTimeUser.HeaderText = "事件用户";
            colTimeUser.DataPropertyName = "EventUser";
            colTimeUser.Width = 80;
            dataGridView1.Columns.Add(colTimeUser);

            // 事件备注
            DataGridViewTextBoxColumn colEventRemark = new DataGridViewTextBoxColumn();
            colEventRemark.Name = "EventRemarks";
            colEventRemark.HeaderText = "事件备注";
            colEventRemark.DataPropertyName = "EventRemarks";
            colEventRemark.Width = 100;
            dataGridView1.Columns.Add(colEventRemark);

            // 事件
            DataGridViewTextBoxColumn colEvent = new DataGridViewTextBoxColumn();
            colEvent.Name = "EventName";
            colEvent.HeaderText = "事件名称";
            colEvent.DataPropertyName = "EventName";
            colEvent.Width = 80;
            dataGridView1.Columns.Add(colEvent);

            // 创建时间
            DataGridViewTextBoxColumn colCreateTime = new DataGridViewTextBoxColumn();
            colCreateTime.Name = "CreateTime";
            colCreateTime.HeaderText = "创建时间";
            colCreateTime.DataPropertyName = "CreateTime";
            colCreateTime.Width = 120;
            dataGridView1.Columns.Add(colCreateTime);

            // 创建用户
            DataGridViewTextBoxColumn colCreateUser = new DataGridViewTextBoxColumn();
            colCreateUser.Name = "CreateUser";
            colCreateUser.HeaderText = "创建用户";
            colCreateUser.DataPropertyName = "CreateUser";
            colCreateUser.Width = 80;
            dataGridView1.Columns.Add(colCreateUser);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 调用 BLL 层的方法查询数据
            currentData = createProductionBll.QueryBatchAndWorkOrder();

            // 补充工艺流程版本、工站版本和描述信息
            foreach (var item in currentData)
            {
                // 获取产品信息
                var product = createProductionBll.GetProductByWorkOrderId(int.Parse(item.WorkOrderNumber));
                if (product != null)
                {
                    // 获取工艺流程信息
                    var processFlow = createProductionBll.GetProcessFlowByFlowId(product.FlowId);
                    if (processFlow != null)
                    {
                        item.ProcessVersion = processFlow.ProcessFlowVersion;
                    }

                    // 获取工站信息
                    var station = createProductionBll.GetStationByStationId(product.StationId);
                    if (station != null)
                    {
                        item.WorkstationNumber = station.StationId.ToString();
                        item.WorkstationVersion = station.StationVersion;
                        item.Description = station.StationDescription;
                    }
                }
            }

            // 将查询结果显示在 DataGridView 中
            dataGridView1.DataSource = currentData;
        }

        private void FilterDataGridView()
        {
            if (currentData == null)
                return;

            string batchIdFilter = textBox1.Text;
            string workOrderFilter = textBox2.Text;
            DateTime? eventDateFilter = null;

            // 尝试将选中的日期字符串转换为 DateTime
            if (!string.IsNullOrEmpty(comboBox1.Text))
            {
                if (DateTime.TryParse(comboBox1.Text, out DateTime eventDate))
                {
                    eventDateFilter = eventDate.Date; // 只保留日期部分
                }
            }

            var filteredData = currentData.AsQueryable();

            if (!string.IsNullOrEmpty(batchIdFilter))
            {
                int batchId;
                if (int.TryParse(batchIdFilter, out batchId))
                {
                    filteredData = filteredData.Where(item => item.BatchId == batchId);
                }
                else
                {
                    filteredData = filteredData.Where(item => false); // 如果输入不是数字，则不显示任何结果
                }
            }

            if (!string.IsNullOrEmpty(workOrderFilter))
            {
                filteredData = filteredData.Where(item => item.WorkOrderNumber.Contains(workOrderFilter));
            }

            if (eventDateFilter.HasValue)
            {
                // 筛选 EventTime 的日期部分与选中的日期匹配的数据
                filteredData = filteredData.Where(item => item.EventTime.Date == eventDateFilter.Value);
            }

            // 更新 DataGridView 的数据源
            dataGridView1.DataSource = null; // 先清除数据源
            dataGridView1.DataSource = filteredData.ToList();
        }

        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            FilterDataGridView();
        }

        private void textBox2_TextChanged_1(object sender, EventArgs e)
        {
            FilterDataGridView();
        }



        private void LoadEventTimes()
        {
            // 调用 BLL 层的方法获取所有的 EventTime 数据（格式化为年月日）
            var eventTimes = createProductionBll.GetAllEventTimes();

            // 将获取到的数据填充到 ComboBox 中
            comboBox1.DataSource = eventTimes;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            FilterDataGridView();
        }

        private void InitializeDataGridView2()
        {
            // 清空现有列
            dataGridView2.Columns.Clear();

            // 设置 DataGridView 的属性
            dataGridView2.AutoGenerateColumns = false;
            dataGridView2.ReadOnly = true; // 设置为只读，防止用户修改数据
            dataGridView2.AllowUserToAddRows = false;
            dataGridView2.AllowUserToDeleteRows = false;
            dataGridView2.RowHeadersVisible = false;
            dataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 设置选择模式为整行选择

            // 添加列
            // 载具号
            DataGridViewTextBoxColumn colCarrierId = new DataGridViewTextBoxColumn();
            colCarrierId.Name = "CarrierId";
            colCarrierId.HeaderText = "载具号";
            colCarrierId.DataPropertyName = "CarrierId";
            colCarrierId.Width = 80;
            dataGridView2.Columns.Add(colCarrierId);

            // 载具类型
            DataGridViewTextBoxColumn colCarrierType = new DataGridViewTextBoxColumn();
            colCarrierType.Name = "CarrierType";
            colCarrierType.HeaderText = "载具类型";
            colCarrierType.DataPropertyName = "CarrierType";
            colCarrierType.Width = 100;
            dataGridView2.Columns.Add(colCarrierType);

            // 载具详细类型
            DataGridViewTextBoxColumn colCarrierDetailedType = new DataGridViewTextBoxColumn();
            colCarrierDetailedType.Name = "DetailedCarrierType";
            colCarrierDetailedType.HeaderText = "载具详细类型";
            colCarrierDetailedType.DataPropertyName = "DetailedCarrierType";
            colCarrierDetailedType.Width = 160;
            dataGridView2.Columns.Add(colCarrierDetailedType);

            // 载具状态
            DataGridViewTextBoxColumn colCarrierStatus = new DataGridViewTextBoxColumn();
            colCarrierStatus.Name = "CarrierStatus";
            colCarrierStatus.HeaderText = "载具状态";
            colCarrierStatus.DataPropertyName = "CarrierStatus";
            colCarrierStatus.Width = 100;
            dataGridView2.Columns.Add(colCarrierStatus);

            // 清洗状态
            DataGridViewTextBoxColumn colCleaningStatus = new DataGridViewTextBoxColumn();
            colCleaningStatus.Name = "CleaningStatus";
            colCleaningStatus.HeaderText = "清洗状态";
            colCleaningStatus.DataPropertyName = "CleaningStatus";
            colCleaningStatus.Width = 80;
            dataGridView2.Columns.Add(colCleaningStatus);

            // 锁定状态
            DataGridViewTextBoxColumn colLockStatus = new DataGridViewTextBoxColumn();
            colLockStatus.Name = "LockStatus";
            colLockStatus.HeaderText = "锁定状态";
            colLockStatus.DataPropertyName = "LockStatus";
            colLockStatus.Width = 100;
            dataGridView2.Columns.Add(colLockStatus);

            // 容量状态
            DataGridViewTextBoxColumn colCapacityStatus = new DataGridViewTextBoxColumn();
            colCapacityStatus.Name = "CapacityStatus";
            colCapacityStatus.HeaderText = "容量状态";
            colCapacityStatus.DataPropertyName = "CapacityStatus";
            colCapacityStatus.Width = 100;
            dataGridView2.Columns.Add(colCapacityStatus);

            // 位置号
            DataGridViewTextBoxColumn colLocationNumber = new DataGridViewTextBoxColumn();
            colLocationNumber.Name = "LocationNumber";
            colLocationNumber.HeaderText = "位置号";
            colLocationNumber.DataPropertyName = "LocationNumber";
            colLocationNumber.Width = 80;
            dataGridView2.Columns.Add(colLocationNumber);

            // 载具容量
            DataGridViewTextBoxColumn colCarrierCapacity = new DataGridViewTextBoxColumn();
            colCarrierCapacity.Name = "CarrierCapacity";
            colCarrierCapacity.HeaderText = "载具容量";
            colCarrierCapacity.DataPropertyName = "CarrierCapacity";
            colCarrierCapacity.Width = 100;
            dataGridView2.Columns.Add(colCarrierCapacity);
        }

        private void LoadCarrierData()
        {
            // 调用 BLL 层的方法查询载具数据
            currentCarrierData = createProductionBll.GetAllCarriers();

            // 将查询结果显示在 DataGridView2 中
            dataGridView2.DataSource = currentCarrierData;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            // 检查是否选中了批次数据和载具数据
            if (dataGridView1.SelectedRows.Count == 0 || dataGridView2.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选中一条批次数据和一条载具数据！");
                return;
            }

            // 获取选中的批次数据和载具数据
            var selectedBatch = dataGridView1.SelectedRows[0].DataBoundItem as QueryBatchAndWorkOrderItem;
            var selectedCarrier = dataGridView2.SelectedRows[0].DataBoundItem as Model.Carrier;

            if (selectedBatch == null || selectedCarrier == null)
            {
                MessageBox.Show("选中的数据无效！");
                return;
            }

            // 更新批次的锁定状态为“已投产”
            selectedBatch.LockStatus = "已投产";

            // 确保在更新批次数据时包含所有必要字段
            var batchModel = new Model.Batch
            {
                BatchId = selectedBatch.BatchId,
                ProductId = int.Parse(selectedBatch.ProductId), // 将字符串转换为整数
                WorkOrderId = int.Parse(selectedBatch.WorkOrderNumber), // 将字符串转换为整数
                TotalProcessId = selectedBatch.TotalProcessId,// 将字符串转换为整数
                BatchType = selectedBatch.BatchType,
                Quantity = selectedBatch.Quantity,
                SubQuantity = selectedBatch.SubQuantity,
                LockStatus = selectedBatch.LockStatus,
                EventTime = selectedBatch.EventTime,
                EventUser = selectedBatch.EventUser,
                EventName = selectedBatch.EventName,
                EventRemarks = selectedCarrier.CarrierId.ToString(), // 将载具 ID 赋值到 EventRemark
                Unit = selectedBatch.Unit
            };

            // 调用 BLL 层的方法更新批次数据
            createProductionBll.UpdateBatch(batchModel);

            // 插入载体列表信息，将选中的载具号传入 DurableSpecId
            createProductionBll.InsertCarrierList(selectedCarrier.CarrierId, selectedBatch.BatchId, selectedCarrier.CarrierId);

            // 刷新 DataGridView1 的数据
            currentData = createProductionBll.QueryBatchAndWorkOrder();

            // 补充工艺流程版本、工站版本和描述信息
            foreach (var item in currentData)
            {
                var product = createProductionBll.GetProductByWorkOrderId(int.Parse(item.WorkOrderNumber));
                if (product != null)
                {
                    var processFlow = createProductionBll.GetProcessFlowByFlowId(product.FlowId);
                    if (processFlow != null)
                    {
                        item.ProcessVersion = processFlow.ProcessFlowVersion;
                    }

                    var station = createProductionBll.GetStationByStationId(product.StationId);
                    if (station != null)
                    {
                        item.WorkstationNumber = station.StationId.ToString();
                        item.WorkstationVersion = station.StationVersion;
                        item.Description = station.StationDescription;
                    }
                }
            }

            dataGridView1.DataSource = currentData;

            MessageBox.Show($"批次 {selectedBatch.BatchId} 投产成功！载具号 {selectedCarrier.CarrierId} 已关联。");

        }
        }
}